<template>
  <ContentWrap style="min-height: 170px;">
  <el-form
    :model="queryParams"
    ref="queryFormRef"
    label-width="auto"
  >
    <!-- 第一行：客户名称、国家地区、行业分类、客户来源 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6">
        <el-form-item label="客户名称" prop="personName">
          <el-input
            v-model="queryParams.personName"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-form-item label="国家地区" prop="country">
          <el-input
            v-model="queryParams.country"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-form-item label="行业分类" prop="industryCode">
          <el-select
            v-model="queryParams.industryCode"
            placeholder="请选择"
            clearable
            teleported="false"
            :popper-options="{ modifiers: [{ name: 'flip', options: { fallbackPlacements: [] } }] }"
            placement="bottom-start"
          >
            <el-option
              v-for="item in industryCode"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-form-item label="客户来源" prop="sourceCode">
          <el-select
            v-model="queryParams.sourceCode"
            placeholder="请选择"
            clearable
            teleported="false"
            :popper-options="{ modifiers: [{ name: 'flip', options: { fallbackPlacements: [] } }] }"
            placement="bottom-start"
            >
              <el-option
                v-for="item in sourceCode"
                :key="item"
                :label="item"
                :value="item"
              />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二行：释放时间 + 查询重置按钮 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :xs="24" :sm="24" :md="12">
        <el-form-item label="出货日期">
          <el-date-picker
            v-model="queryParams.shipDateRange"
            type="datetimerange"
            range-separator="到"
            start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm"
            style="width: 100%;"
            />
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12">
        <div div style="display: flex; justify-content: flex-start; gap: 12px; align-items: center; ">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button plain class="blue-btn" @click="resetQuery">重置</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 第三行：领取、分配、释放到公海客户、删除 -->
    <el-row class="mt-4">
      <el-col :span="24">
        <div style="display: flex; flex-wrap: wrap; gap: 12px;">
          <el-button type="primary" @click="pickUp">领取</el-button>
          <el-button plain class="blue-btn" @click="allocation">分配</el-button>
          <el-button plain class="blue-btn" @click="openReleaseRuleDialog">释放到公海规则</el-button>
          <el-button plain class="blue-btn red-hover" @click="handleBatchDelete">删除</el-button>
        </div>
      </el-col>
    </el-row>

  </el-form>
</ContentWrap>
  <!-- 分配客户 -->
<el-dialog v-model="allocationDialogVisible" title="分配" width="500px">
  <el-form>
<el-form-item label="业务员">
  <el-popover
    placement="bottom-start"
    width="300"
    trigger="click"
    v-model:visible="userTreeVisible"
  >
    <el-tree
      :data="userTreeData"
      node-key="id"
      :props="{ children: 'children', label: 'label' }"
      @node-click="handleUserSelect"
      highlight-current
      default-expand-all
    />
    <template #reference>
      <el-input
        v-model="selectedUserLabel"
        placeholder="请选择业务员"
        readonly
        suffix-icon="el-icon-arrow-down"
      />
    </template>
  </el-popover>
</el-form-item>

  </el-form>
  <template #footer>
    <el-button @click="allocationDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handleAllocation">确定</el-button>
  </template>
</el-dialog>


  <!-- 列表 -->
  <ContentWrap>
    <el-table
    v-loading="loading"
    :data="list"
    :stripe="true"
    :show-overflow-tooltip="true"
    :header-cell-style="{
      'background-color': '#f2f2f2',
      'color': '#333'
    }"
    @selection-change="handleSelectionChange"

  >
    <!-- 勾选框列，表头与内容垂直居中对齐 -->
    <el-table-column
      type="selection"
      width="55"
      align="center"
      :header-cell-style="{ padding: '0', 'vertical-align': 'middle' }"
      :cell-style="{ padding: '0', 'vertical-align': 'middle' }"
    />
    <!-- 序号列 -->
    <el-table-column type="index" label="序号" width="60" align="center" />
    <!-- 客户编码 -->
    <el-table-column label="客户编码" align="center" prop="code" />
    <!-- 客户名称，带跳转链接 -->
    <el-table-column label="客户名称" align="center" prop="personName">
      <template #default="scope">
          <span 
            class="link-type" 
            style="color: blue; cursor: pointer;" 
            @click="handleNameClick(scope.row)"
          >
            {{ scope.row.personName || scope.row.companyName }}
          </span>
        </template>
    </el-table-column>
    <!-- 国家地区 -->
    <el-table-column label="国家地区" align="center" prop="country" />
    <!-- 客户来源 -->
    <el-table-column label="客户来源" align="center" prop="sourceCode" />
    <!-- 客户星级 -->
    <el-table-column label="客户星级" align="center" prop="starCode" />
    <!-- 行业分类 -->
    <el-table-column label="行业分类" align="center" prop="industryCode" />
    <!-- 释放时间 -->
    <el-table-column
      label="释放时间"
      align="center"
      prop="releaseTime"
      :formatter="dateFormatter"
      width="180px"
    />
  </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

<!-- 释放到公海规则 -->
  <el-dialog v-model="releaseRuleDialogVisible" title="释放到公海规则" width="600px" @close="onReleaseRuleClose">
  <el-form :model="releaseRuleForm" label-width="200px">
    <el-form-item label="未成交客户" prop="unclosedCustomerDays">
      <el-input-number
v-model="releaseRuleForm.unclosedCustomerDays"
      @input="val => onInputPositive(val, 'unclosedCustomerDays')"
      :min="0" :max="365" :controls="false" style="width: 80px" /> 天未跟进释放到公海
    </el-form-item>
    <el-form-item label="已成交客户" prop="closedCustomerDays">
      <el-input-number
v-model="releaseRuleForm.closedCustomerDays" 
      @input="val => onInputPositive(val, 'closedCustomerDays')"
      :min="0" :max="365" :controls="false" style="width: 80px"/> 天未跟进释放到公海
    </el-form-item>
    <el-form-item label="每个业务员最大客户保有量" prop="maxCustomerHolding">
      <el-input-number
v-model="releaseRuleForm.maxCustomerHolding" 
      @input="val => onInputPositive(val, 'maxCustomerHolding')"
      :min="0" :max="10000" :controls="false" style="width: 80px"/> 个，超出则无法新增或领取客户
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="text-center">
    <el-button @click="releaseRuleDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="onReleaseRuleSave">保存</el-button>
  </div>
  </template>
</el-dialog>
  <!-- 表单弹窗：添加/修改 -->
  <CustHighSeasForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { CustHighSeasApi, CustHighSeasVO } from '@/api/customermanager/custhighseas'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import CustHighSeasForm from './CustHighSeasForm.vue' // 导入表单组件
import { onActivated } from 'vue'

/** 客户公海 列表 */
defineOptions({ name: 'CustHighSeas' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustHighSeasVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  personName: undefined,
  country: undefined,
  industryCode: undefined,
  sourceCode: undefined,
  pageNo: 1,
  pageSize: 10,
  startReleaseTime: undefined,
  endReleaseTime: undefined,
  releaseTime: undefined,
  shipDateRange: [] // 用于绑定 datetimerange 组件
})



//********************分配公海客户**************************** */
import { CustInfoApi } from '@/api/customermanager/custmanage'; // 确保路径正确
import { ref, reactive } from 'vue'
import request from '@/config/axios' // 引入axios


// 控制分配弹窗显示
const allocationDialogVisible = ref(false)

// 存储树形数据
const userTreeData = ref<any[]>([])

// 存储选中的业务员
const selectedUser = ref<any>(null)
const selectedUserLabel = ref('')


const userTreeVisible = ref(false);  // 控制树形结构的显示

// 存储选中的客户
const selectedRows = ref<CustHighSeasVO[]>([])

// 打开树形结构
const openUserTree = () => {
  userTreeVisible.value = true; // 展示树形结构
};

// 获取选中的客户
const handleSelectionChange = (rows: CustHighSeasVO[]) => {
  selectedRows.value = rows
 console.log(
  '选中的客户信息:',
  selectedRows.value.map(row => ({
    id: row.id,
    name: row.personName  || '未知名称'
  }))
)
}

// 选择业务员的处理函数
const handleUserSelect = (node: any) => {
  console.log('点击了节点:', node)
  if (!node.children || node.children.length === 0) {
    selectedUser.value = node
    console.log('选中的业务员:', selectedUser.value)
    selectedUserLabel.value = node.label // 展示到 input 上
    userTreeVisible.value = false        // 关闭 popover
  }
}
// 获取业务员树数据
const loadUserTree = async () => {
  try {
    const res = await CustInfoApi.getSalesmanTree(); // 获取业务员树的数据
    if (res && res.length > 0) {
      userTreeData.value = res;  // 设置树形数据
    }
  } catch (error) {
    ElMessage.error('加载业务员树数据失败');
  }
};

// 分配客户函数
const handleAllocation = async () => {
  if (!selectedUser.value) {
    ElMessage.warning('请先选择一个业务员')
    return
  }

  const custIds = selectedRows.value.map(row => row.custId)
  if (custIds.length === 0) {
    ElMessage.warning('请先选择要分配的客户')
    return
  }
  try {
    console.log('分配客户参数:', custIds, selectedUser.value.id)
    await CustInfoApi.updateSalesman({ ids: custIds, salesmanId: selectedUser.value.id })
    // await request.post({
    //   url: '/business/cust-info/updateSalesman', // 分配客户的API
    //   data: {
    //     custIds,                      // 客户ID数组
    //     userId: selectedUser.value.id // 被分配的业务员ID
    //   }
    // })

    ElMessage.success('分配成功')
    await CustHighSeasApi.batchDeleteCustHighSeas(custIds)//删除公海客户对应的用户
    allocationDialogVisible.value = false // 关闭弹窗
    getList() // 刷新列表
  } catch (e: any) {
    console.error('分配失败:', e)
    ElMessage.error(e?.message || '分配失败')
  }
}

// 打开分配弹窗并加载用户数据
const allocation = async () => {
   allocationDialogVisible.value = true;
  try {
    // 获取业务员树的数据
    const res = await CustInfoApi.getSalesmanTree(); 

    // 检查响应是否包含数据
    if (!res || res.length === 0) {
      throw new Error('API 请求失败，未获取到数据');
    }

    // 如果数据结构符合预期，直接赋值给 userTreeData
    userTreeData.value = res; // 直接赋值给树形数据

    console.log("业务员树数据加载成功:", res);  // 输出数据，确保树形数据正确加载
  } catch (error) {
    console.error("加载业务员树数据失败:", error); // 输出详细错误信息
    ElMessage.error(`加载业务员树数据失败: ${error.message || error}`);
  }
};



//******************************************************** */


// 释放到公海规则弹窗相关
const releaseRuleDialogVisible = ref(false)
const releaseRuleForm = reactive({
  unclosedCustomerDays: 10,
  closedCustomerDays: 20,
  maxCustomerHolding: 30
})
// 获取规则数据的 API 方法
const getReleaseRules = async (): Promise<ReleaseRulesVO> => {
  // 直接就是业务字段，无需判断 code
  return await request.get({ url: '/business/release-rules/get-simple' })
}
//打开弹窗前加载数据库数据
const openReleaseRuleDialog = async () => {
 try {
    const data = await getReleaseRules()

    // 确保 data 存在才赋值（理论上你已经确认存在）
    releaseRuleForm.unclosedCustomerDays = data.unclosedCustomerDays
    releaseRuleForm.closedCustomerDays = data.closedCustomerDays
    releaseRuleForm.maxCustomerHolding = data.maxCustomerHolding

    releaseRuleDialogVisible.value = true
  } catch (err: any) {
    console.error('加载释放规则失败:', err)
    ElMessage.error('加载释放规则失败: ' + (err.message || '未知错误'))
  }
}
const onInputPositive = (val: any, field: keyof typeof releaseRuleForm) => {
  // 先用正则判断是否为非负整数
  const reg = /^\d+$/

  if (!reg.test(val)) {
    ElMessage.warning('只能输入非负整数')
    releaseRuleForm[field] = ''
    return
  }

  // 通过后赋值
  releaseRuleForm[field] = Number(val)
}


// 页面初始化时加载规则
onMounted(async () => {
  const data = await getReleaseRules()
   console.log('接口返回的数据：', data)
  // 将返回值赋给表单
  releaseRuleForm.unclosedCustomerDays = data.unclosedCustomerDays
  releaseRuleForm.closedCustomerDays = data.closedCustomerDays
  releaseRuleForm.maxCustomerHolding = data.maxCustomerHolding
})



// 关闭弹窗
const onReleaseRuleClose = () => {
  releaseRuleDialogVisible.value = false
}

// 保存规则
const onReleaseRuleSave = async () => {
const { unclosedCustomerDays, closedCustomerDays, maxCustomerHolding } = releaseRuleForm

  if (unclosedCustomerDays < 0 || closedCustomerDays < 0 || maxCustomerHolding < 0) {
    ElMessage.warning('输入的天数或客户数不能为负数')
    return
  }
  try {
    await CustHighSeasApi.updateReleaseRules(releaseRuleForm)
    message.success('保存成功')
    releaseRuleDialogVisible.value = false
  } catch (error: any) {
    message.error(error.message || '保存失败')
  }
}
// ************************************

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const [start, end] = queryParams.shipDateRange ?? []

    const paramsToSend = {
      ...queryParams,
      startReleaseTime: start,
      endReleaseTime: end,
      shipDateRange: undefined // 移除无关字段
    }
    const data = await CustHighSeasApi.getCustHighSeasPage(paramsToSend)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}


const queryFormRef = ref()
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
   queryParams.shipDateRange = []
  handleQuery()
}


/** 领取操作按钮（带确认和弹窗提示） */
const pickUp = async () => {
  const selectedIds = selectedRows.value.map(row => row.custId)

  if (selectedIds.length === 0) {
    await ElMessageBox.alert('请先选择要领取的客户', '提示', {
      type: 'info',
      confirmButtonText: '确定',
    })
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要领取选中的 ${selectedIds.length} 个客户吗？`,
      '确认领取',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
    )

    // ❗️注意：这一步如果后端返回 code ≠ 0，会直接抛异常
    await CustHighSeasApi.pickUpCustomers(selectedIds)

    await ElMessageBox.alert('领取成功', '成功', {
      type: 'success',
      confirmButtonText: '确定',
    })

    getList()
  } catch (error: any) {
  if (error === 'cancel' || error === 'close') return

  const errorMessage = error?.message || '领取失败'
  await ElMessageBox.alert(errorMessage, '领取失败', {
    type: 'error',
    confirmButtonText: '确定',
  })
}
}



/** 释放到公海规则操作按钮 */
const rule = async () => {
  releaseRuleDialogVisible.value = true
}


/** 多选删除 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据！')
    return
  }

  try {
    await message.delConfirm('确定要删除选中的客户吗？')
    const custIds = selectedRows.value.map(item => item.custId)
    await CustHighSeasApi.batchDeleteCustHighSeas(custIds)
    message.success('删除成功！')
    getList()
  } catch (e) {}
}


const router = useRouter()// 使用 useRouter 进行路由跳转，传递 cust_id 参数

const handleNameClick = (row: CustHighSeasVO) => {
  router.push({
    name: 'CustFollow', // 使用路由名称代替路径
    //path: '/customer_manager/cust-follow',
    query: { 
      cust_id: row.custId,
      cust_name: row.personName
    }
  })
}

// 下拉选项
const industryCode = ref<string[]>([])
const sourceCode = ref<string[]>([])

/** 加载所有下拉选项数据 */
const loadAllDropdownOptions = async () => {
  try {
    const [
      industryData,
      sourceData,
    ] = await Promise.all([
      CustHighSeasApi.getIndustryCode(),
      CustHighSeasApi.getSourceCode(),
    ])

    industryCode.value = Array.isArray(industryData) ? industryData : []
    sourceCode.value = Array.isArray(sourceData) ? sourceData : []

  } catch (error) {
    console.error('加载下拉选项失败:', error)
  }
}


/** 初始化 **/
onMounted(() => {
  loadUserTree();
  loadAllDropdownOptions();
})

// 页面重新进入时自动刷新数据
onActivated(() => {
  getList()
})
</script>


<style scoped>
/* 表头 checkbox 居中：Element Plus 特有类 */
::v-deep(.el-table .el-table-column--selection .cell) {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 0;
}

.blue-btn {
  border: 1px solid #409eff;
  color: #409eff;
  background-color: white;
  transition: all 0.3s ease;
}

.blue-btn:hover {
  background-color: #409eff;
  color: white;
}

/* 删除按钮特有：默认蓝字白底，悬停红底白字 */
.red-hover {
  border-color: #409eff; /* 默认蓝边 */
  color: #409eff;        /* 默认蓝字 */
  background-color: white;
  transition: all 0.3s ease;
}

.red-hover:hover {
  background-color: #ff4d4f; /* 红底 */
  color: white;              /* 白字 */
  border-color: #ff4d4f;     /* 红边 */
}


</style>

